# -*- coding: utf-8 -*-
"""
Created on Tue Jun 11 12:46:30 2024

@author: 29865
"""

import pandas as pd
from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt

value_table = pd.read_excel('IDX_Idxtrd.xlsx')

def month_changed(date_str1, date_str2, format='%Y-%m-%d'):
    """
    判断两个日期月份是否发生变化
    Parameters
    ----------
    date_str1 : str
        日期1.
    date_str2 : str
        日期2.
    format : str
       日期格式化字符串. The default is '%Y-%m-%d'.
    Returns
    -------
    bool
        True:月份发生变化.
        False:月份未发生变化
    """
    date1 = datetime.strptime(date_str1, format)  
    date2 = datetime.strptime(date_str2, format)
    if date1.month != date2.month:
        return True
    else:
        return False

# 获取每月的开始日期和结束日期列表
month_start_list = ['2017-01-03']
month_end_list = []

for i in range(1, len(value_table) - 1):
    j = i + 1
    month_1 = value_table.iloc[i, 1]
    month_2 = value_table.iloc[j, 1]
    if month_changed(month_1, month_2):
        month_end_list.append(value_table.iloc[i, 1])
        month_start_list.append(value_table.iloc[j, 1])

month_end_list.append('2017-12-29')


# 计算月收益率并绘图
X = []
Y = []
for i in range(len(month_start_list)):
    start_value = value_table.loc[value_table['Idxtrd01'].values == month_start_list[i], 'Idxtrd05'].values
    end_value = value_table.loc[value_table['Idxtrd01'].values == month_end_list[i], 'Idxtrd05'].values
    month_yield = ((end_value - start_value) / start_value)[0]
    X.append(i + 1)
    Y.append(month_yield)

X = np.array(X)
Y = np.array(Y)
plt.rcParams['font.sans-serif'] = 'SimHei'  # 设置字体为SimHei
plt.rcParams['axes.unicode_minus'] = False  # 解决负号“-”显示异常
plt.title('月收益率变化曲线')
plt.plot(X, Y)